/**
 * Plan table.
 */
var planTable = {};
var prefix = "o:p:";
var s_key = "o:p:s";

function gettime() {
	"use strict";
	var d = new Date();
	return d.toUTCString();
}

function defaultCallback(err) {
	if (err) {
		console.error("taskTable redis error:" + err);
	}
}

planTable.add = function(context, plan, callback) {
	"use strict";
	var redis = context.redis;
	if (!callback) {
		callback = defaultCallback;
	}
	
	var key = prefix + plan.id;
	plan.createtime = gettime();

	context.beginMulti();
	redis.sadd(s_key, plan.id, defaultCallback);
	redis.hmset(key, plan, callback);
	context.endMulti(defaultCallback);
};

planTable.addFields = function(context, planId, field, value, callback) {
	"use strict";
	var redis = context.redis;
	if (!callback) {
		callback = defaultCallback;
	}
	
	var key = prefix + planId;
	redis.hset(key,field, value, callback);
};
	

planTable.load = function(context, id, callback) {
	"use strict";
	var redis = context.redis;
	if (!callback) {
		callback = defaultCallback;
	}
	
	var key = prefix + id;
	redis.hgetall(key, callback);
};

planTable.loadFields = function(context, id, fields, callback) {
	"use strict";
	var redis = context.redis;
	
	var key = prefix + id;

	redis.hmget(key, fields, callback);
};

planTable.del = function(context, id, callback) {
	"use strict";
	var redis = context.redis;
	if (!callback) {
		callback = defaultCallback;
	}
	
	var key = prefix + id;
	context.beginMulti();
	redis.srem(s_key, id, defaultCallback);
	redis.del(key, callback);
	context.endMulti(defaultCallback);
};

planTable.scan = function(context, cursor, count, callback) {
	"use strict";
	var redis = context.redis;
	if (!callback) {
		callback = defaultCallback;
	}
	
	redis.sscan([s_key, cursor, "COUNT", count], callback);
};

planTable.count = function(context, callback) {
	"use strict";
	var redis = context.redis;
	if (!callback) {
		callback = defaultCallback;
	}
	
	redis.scard(s_key, callback);
};

module.exports = planTable;